package com.mypage.view.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.mobile.R;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.view.activity.ChosePerson;
import com.cloudcc.mobile.view.activity.TaskManagementActivty;
import com.cloudcc.mobile.weight.CustomProgressDialog;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.litesuits.android.async.Log;
import com.mypage.utils.NetworkDetector;

import org.json.JSONException;
import org.json.JSONObject;

import static com.cloudcc.mobile.R.id.btnApprovalPerson;
import static com.cloudcc.mobile.R.id.textViewAdmin;

public class MyApproval extends Activity implements OnClickListener {
	private ImageView mBack;
	private TextView mAlerdyAppPerson,title,titleRight,mApprovalPerson;
//	private Button btnSure, btnCancel;
	private String personId;
	private TextView textView;
	private EditText edit;
	private String content;
	private String workItemId;
	private String personname;
	private CustomProgressDialog progressDialog;
	private String isNew="";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_approval);
		workItemId = getIntent().getStringExtra("workItemId");
		personname = getIntent().getStringExtra("personname");
		isNew = getIntent().getStringExtra("weizhi");
		progressDialog = CustomProgressDialog.createDialog(this);
		initViews();
		initListener();

	}

	/**
	 * dialog开始显示
	 */
	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(context);
			progressDialog.setCancelable(true);
			progressDialog.setCanceledOnTouchOutside(false);
			// progressDialog.setMessage("正在加载中...");
		}
		progressDialog.show();
	}

	/**
	 * 停止dialog
	 */
	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	private void initViews() {
		// TODO Auto-generated method stub
		mBack = (ImageView) findViewById(R.id.bar_back);
		mAlerdyAppPerson = (TextView) findViewById(textViewAdmin);
		mApprovalPerson = (TextView) findViewById(btnApprovalPerson);
		edit = (EditText) findViewById(R.id.descEditText);
		textView = (TextView) findViewById(R.id.desTextView);
		title = (TextView) findViewById(R.id.bar_title_textchongxin);
		titleRight = (TextView) findViewById(R.id.bar_right);
		title.setText("重新分配");
		RunTimeManager.getInstance().getUserName();
		mAlerdyAppPerson.setText(RunTimeManager.getInstance().getUserName());
		titleRight.setEnabled(false);
	}

	private void initListener() {
		// TODO Auto-generated method stub
		mBack.setOnClickListener(this);
		mApprovalPerson.setOnClickListener(this);
		titleRight.setOnClickListener(this);
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.bar_back:
			finish();
			break;
		case btnApprovalPerson:

			Intent intent = new Intent();
			intent.setClass(MyApproval.this, ChosePerson.class);

			startActivityForResult(intent, 0);
			break;
		//右边的提交
		case R.id.bar_right:
			titleRight.setText(getResources().getString(R.string.chulizhong));
			content = edit.getText().toString().trim();
			// if (content.length() == 0) {
			// Toast.makeText(MyApproval.this, "描述为空", Toast.LENGTH_SHORT)
			// .show();
			// } else if (personId == null) {
			// Toast.makeText(MyApproval.this, "批准人为空", Toast.LENGTH_SHORT)
			// .show();
			// } else
			if (!NetworkDetector.detect(MyApproval.this)) {
				Toast.makeText(MyApproval.this, "当前网络不可用....",
						Toast.LENGTH_SHORT).show();
			} else {
				if("xiangqing".equals(isNew)){
					netWorkOld(content);
				}else {
					netWork(content);
				}
				progressDialog.setCanceledOnTouchOutside(false);
				startProgressDialog();
			}
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch (resultCode) {
		case RESULT_OK:
			String name = data.getStringExtra("name");
			personId = data.getStringExtra("userId");
			Log.d("AAAAAAAAAAAAAAAAAA", name);
			if(personId.length()>0){
				mApprovalPerson.setText(name);
				mApprovalPerson.setBackgroundColor(0);
				mApprovalPerson.setTextColor(getResources().getColor(R.color.shenpiren));
				titleRight.setBackground(getResources().getDrawable(R.drawable.biankuang_tijiao));
				titleRight.setTextColor(getResources().getColor(R.color.dingbu_color));
				titleRight.setEnabled(true);
			}else{
				titleRight.setTextColor(getResources().getColor(R.color.tijiao));
				titleRight.setBackground(getResources().getDrawable(R.drawable.biankuang_tijiaoan));
				titleRight.setEnabled(false);
				mApprovalPerson.setBackgroundColor(getResources().getColor(R.color.dingbu_color));
				mApprovalPerson.setTextColor(getResources().getColor(R.color.shenpiren));
			}
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	Context context;

	public void netWork(String content) {

		// 重新分配
		HttpUtils utils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("userId",
				UserManager.getManager().getUser().userId);
		params.addBodyParameter("binding", RunTimeManager.getInstance()
				.getServerBinding());
		params.addBodyParameter("serviceName", "ajaxProcessMassThread");
		params.addBodyParameter("workItemId", workItemId);
		params.addBodyParameter("actionType", "Reassign");
		params.addBodyParameter("comments", content);
		params.addBodyParameter("fprId", personId);
		Log.d("-------------------------", "//workItemId=" + workItemId
				+ "//Approved=" + "Approved" + "//content=" + content
				+ "//personId=" + personId);
		Log.d("hahahha", UrlManager.getInterfaceUrl() + params.toString());
		utils.send(HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub
						stopProgressDialog();
						Intent intent = new Intent(MyApproval.this,
								TaskManagementActivty.class);
//						if(workItemId.length()>30) {
//							intent.putExtra("chongxin", "chongxinmore");
//						}else{
						intent.putExtra("chongxinshibai","chongxin");
//						}
						startActivity(intent);
						sendBroadcast(new Intent().setAction("finish"));
						finish();

					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						// TODO Auto-generated method stub
						// String result = arg0.result;
						Log.d("-------------------------", "刘永杰" + arg0);
						sendBroadcast(new Intent().setAction("taskfinish"));
						stopProgressDialog();
						Intent intent = new Intent(MyApproval.this,
								TaskManagementActivty.class);
						TaskManagementActivty.instance.finish();
						try {
							ApprovalPendingActivity.instance.finish();
						} catch (Exception e) {
							e.printStackTrace();
						}
						if(workItemId.length()>30) {
							intent.putExtra("taskfinish", "taskfinish");
						}else{
							intent.putExtra("taskfinish","taskfinish");
						}
						startActivity(intent);
						sendBroadcast(new Intent().setAction("finish"));
						finish();
					}
				});

	}

	public void netWorkOld(String content) {

		// 重新分配
		HttpUtils utils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("binding", RunTimeManager.getInstance()
				.getServerBinding());
		params.addBodyParameter("serviceName", "doReassign");
		params.addBodyParameter("data", createJson());
//		params.addBodyParameter("fprId", personId);
		Log.d("-------------------------", "//workItemId=" + workItemId
				+ "//Approved=" + "Approved" + "//content=" + content
				+ "//personId=" + personId);
		Log.d("hahahha", UrlManager.getInterfaceUrl() + params.toString());
		utils.send(HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub
						stopProgressDialog();
						Intent intent = new Intent(MyApproval.this,
								TaskManagementActivty.class);
//						if(workItemId.length()>30) {
//							intent.putExtra("chongxin", "chongxinmore");
//						}else{
						intent.putExtra("chongxinshibai","chongxin");
//						}
						startActivity(intent);
						sendBroadcast(new Intent().setAction("finish"));
						finish();

					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						// TODO Auto-generated method stub
						// String result = arg0.result;
						Log.d("-------------------------", "刘永杰" + arg0);
						sendBroadcast(new Intent().setAction("taskfinish"));
						stopProgressDialog();
						Intent intent = new Intent(MyApproval.this,
								TaskManagementActivty.class);
						TaskManagementActivty.instance.finish();
						try {
							ApprovalPendingActivity.instance.finish();
						} catch (Exception e) {
							e.printStackTrace();
						}
						intent.putExtra("taskfinish","xiangqingpizhun");
						startActivity(intent);
						sendBroadcast(new Intent().setAction("finish"));
						finish();
					}
				});
	}

	public String createJson() {
		JSONObject object = new JSONObject();
		try {
			object.put("workItemId", workItemId);
			object.put("comments", content);
			object.put("fprId", personId);
			// Log.d("/////////////////", object.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return object.toString();

	}
}
